package com.monolithiot.sso.service.impl;

import com.monolithiot.sso.common.context.Constants;
import com.monolithiot.sso.common.exception.ServiceUnforeseenException;
import com.monolithiot.sso.dao.BaseMapper;
import com.monolithiot.sso.service.BaseService;

import java.util.List;

/**
 * 2018/11/12 Create by 郭文梁
 * BaseServiceImpl
 * 基础业务组件实现
 *
 * @author 郭文梁
 * @date 2018/11/12
 */
public abstract class BaseServiceImpl<T> implements BaseService<T> {
    private static final String DEFAULT_ORDER_FIELD = "id";
    private static final String DEFAULT_ORDER_DIRECTION = Constants.SQL.DESC;

    /**
     * 获得Mapper组件，由子类实现，子类注入Mapper后返回即可
     *
     * @return Mapper组件
     */
    abstract BaseMapper<T> getMapper();

    @Override
    public List<T> list() {
        return getMapper().selectAll();
    }

    @Override
    public List<T> list(int page, int size) {
        return getMapper().list((page - 1) * size, size, DEFAULT_ORDER_FIELD, DEFAULT_ORDER_DIRECTION);
    }

    @Override
    public int totalCount() {
        return getMapper().selectCount(null);
    }

    @Override
    public T save(T o) {
        int result = getMapper().insert(o);
        return result > 0 ? o : null;
    }

    @Override
    public T delete(T o) {
        T result = getMapper().selectOne(o);
        if (result == null) {
            return null;
        }
        int rows = getMapper().delete(result);
        return rows > 0 ? result : null;
    }

    @Override
    public T deleteById(Object id) {
        T t = getMapper().selectByPrimaryKey(id);
        if (t == null) {
            return null;
        }
        return delete(t);
    }

    @Override
    public List<T> search(T condition) {
        return getMapper().select(condition);
    }

    @Override
    public T get(Object id) {
        return getMapper().selectByPrimaryKey(id);
    }

    @Override
    public T update(T o) {
        int data = getMapper().updateByPrimaryKey(o);
        if (data > 0) {
            return o;
        } else {
            throw new ServiceUnforeseenException("Unable to update [" + o + "]");
        }
    }

    @Override
    public boolean exists(T query) {
        List<T> res = getMapper().select(query);
        return !(res == null || res.isEmpty());
    }
}
